﻿#include "ssLeHttpClient.h"
#include "log/ssLogThread.h"

namespace StarSeeker
{

static void http_request_cb(struct evhttp_request *req, void *arg)
{
	ssLeHttpClient* phttp = (ssLeHttpClient*)arg;
	ev_ssize_t len = 0;
	if (req)
	{
		evbuffer *evbuf = evhttp_request_get_input_buffer(req);
		if (evbuf)
		{
			len = evbuffer_get_length(evbuf);
			if (len > 0)
			{
				char buf[1024 * 2] = { 0 };
				int s = evbuffer_remove(req->input_buffer, &buf, sizeof(buf)-1);
				if (s > 0 && s < sizeof(buf))
				{
					buf[s] = '\0';
					phttp->OnResponse(buf);
				}
				SS_LOG->Print(buf);
				//linux下此函数会自动调用，win下不调用会内存泄漏
				evhttp_request_free(req);
			}
		}
	}
	//evhttp_connection_free(m_conn);
	//event_base_loopbreak((struct event_base *)arg);
	phttp->BreakLoop();
}


ssLeHttpClient::ssLeHttpClient()
{
	m_base = 0;
	m_conn = 0;
}

ssLeHttpClient::~ssLeHttpClient()
{
	if (m_conn)
		evhttp_connection_free(m_conn);
	if (m_base)
		event_base_free(m_base);
}

bool ssLeHttpClient::StartConnect(const char* ip, unsigned short port)
{
	m_base = event_base_new();
	if (!m_base)
	{
		SS_LOG->Print("Couldn't create an event_base.");
		return false;
	}
	m_conn = evhttp_connection_base_new(m_base, NULL, ip, port);
	if (!m_conn)
	{
		SS_LOG->Print("couldn't create evhttp connection.");
		return false;
	}
	evhttp_connection_set_timeout(m_conn, 1);
	SS_LOG->PrintEx("http client %s:%d", ip, port);
	return true;
}

void ssLeHttpClient::BreakLoop()
{
	if (m_base)
	{
		event_base_loopbreak(m_base);
	}
}

evhttp_request* ssLeHttpClient::MakeRequest(const char* param)
{
	evhttp_request* req = evhttp_request_new(http_request_cb, this);
	//
	evhttp_add_header(req->output_headers, "Host", "localhost");
	evhttp_add_header(req->output_headers, "Connection", "close");
	//
	evhttp_make_request(m_conn, req, EVHTTP_REQ_GET, param/*"/"*/);
	event_base_dispatch(m_base);
	return req;
}

void ssLeHttpClient::OnResponse(const char* param)
{

}

}
